﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Xsl;


namespace trx2html2012
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            txtStatus.Text = "";
        }

        private void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                txtStatus.Text = "";
                txtStatus.Text = "Creating HTML reports of VSTS TestRuns.";

                txtStatus.Text += Environment.NewLine + "version:" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + Environment.NewLine;
                if (txtFileName.Text.Trim().Length == 0)
                {
                    MessageBox.Show("Please enter path");
                    return;
                }

                string fileName = txtFileName.Text.Trim();
                Transform(fileName, PrepareXsl());
                txtStatus.Text += Environment.NewLine + "Tranformation Succeed. OutputFile: " + fileName + ".htm\n" + Environment.NewLine;

            }
            catch (Exception exec)
            {
                MessageBox.Show(exec.Message);
            }
        }

        private static string GetTxtBtwn(string input, string start, string end, int startIndex, bool UseLastIndexOf)
        {
            int index1 = UseLastIndexOf ? input.LastIndexOf(start, startIndex) :
                                          input.IndexOf(start, startIndex);
            if (index1 == -1) return "";
            index1 += start.Length;
            int index2 = input.IndexOf(end, index1);
            if (index2 == -1) return input.Substring(index1);
            return input.Substring(index1, index2 - index1);
        }
        private static void Transform(string fileName, XmlDocument xsl)
        {
            XslCompiledTransform x = new XslCompiledTransform();
            x.Load(xsl, new XsltSettings(true, true), null);
            string NEWFILENAME = "";
            try
            {
                string filedata = System.IO.File.ReadAllText(fileName);
                string sdata = GetTxtBtwn(filedata, "xmlns=", ">", filedata.IndexOf("xmlns="), false);

                filedata = filedata.Replace("xmlns=" + sdata, "");

                string dirname = System.IO.Path.GetDirectoryName(fileName);
                System.IO.File.WriteAllText((dirname + "\\test1.trx"), filedata);

                NEWFILENAME = (dirname + "\\test1.trx");
            }
            catch { NEWFILENAME = fileName; }
            x.Transform(NEWFILENAME, fileName + ".htm");
            System.Diagnostics.Process.Start(fileName + ".htm");
        }

        private static XmlDocument PrepareXsl()
        {
            XmlDocument xslDoc = new XmlDocument();
            //xslDoc.Load(ResourceReader.StreamFromResource("OrcasTRX.xslt"));
            xslDoc.Load(ResourceReader.StreamFromResource("vs2012.xslt"));
            IncludeStyle(xslDoc);
            IncludeScript(xslDoc);
            return xslDoc;
        }

        private static void IncludeScript(XmlDocument xslDoc)
        {
            XmlNode scriptEl = xslDoc.GetElementsByTagName("script")[0];
            XmlAttribute scriptSrc = scriptEl.Attributes["src"];
            string script = ResourceReader.LoadTextFromResource(scriptSrc.Value);
            scriptEl.Attributes.Remove(scriptSrc);
#if !DEBUG
            script = script.Replace(";\r\n", "; ");
            script = script.Replace(",\r\n", ", ");
            script = script.Replace("}\r\n", "} ");
#endif
            scriptEl.InnerText = script;
        }

        private static void IncludeStyle(XmlDocument xslDoc)
        {
            XmlNode headNode = xslDoc.GetElementsByTagName("head")[0];
            XmlNode linkNode = xslDoc.GetElementsByTagName("link")[0];
            XmlElement styleEl = xslDoc.CreateElement("style");
            styleEl.InnerText = ResourceReader.LoadTextFromResource(linkNode.Attributes["href"].Value);
            headNode.ReplaceChild(styleEl, linkNode);
        }

    }
}
